<?php

namespace App\Console\Commands;

use App\Http\Controllers\Resource\YtysController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceTypeExternal;
use App\Models\ResourceYtys;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 *云图有声
 */
class YtysMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:YtysMysqlData

    protected $limit = 100; //每页限制条数
    protected $up_start_page = 1; //开始页，默认为 1
    protected $resource_business_id = 3; //资源商id



    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:YtysMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步云图有声数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('ytyscmdlog')->debug('资源商不存在或已被删除');
            die;
        }
        try {
            //先同步类型
            $obj = new YtysController();
            $resourceModel = new ResourceYtys();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $data_type = $obj->getType();
            if ($data_type) {
                $result_id = '';
                foreach ($data_type['data'] as $key => $val) {

                    $val['class_type_id'] = $val['classTypeId'];
                    $val['parent_id'] = $val['parentId'];
                    $val['parent_name'] = $val['parentName'];
                    $val['resource_business_id'] = $this->resource_business_id;
                    $val['big_type_id'] = 2;
                    $result = $resourceTypeExternalModel->getTypeNameNoAdd($val);

                    $result_id .= $result . '、';
                }
                trim($result_id, '、');
                Log::channel('ytyscmdlog')->debug('云图有声数据类型同步完成: ' . $result_id);
            }
            $book_type_relation = $obj->getBookTypeRelation();
            if ($book_type_relation) {
                $book_type_relation = array_column($book_type_relation['data'], 'classTypeId', 'bookId'); //获取书籍与类型的关系，类型为键值，书籍键名
            }
            //获取我们自己的所有的大类
            $external_type_info = $resourceTypeExternalModel->select('class_type_id', 'id')->where('resource_business_id', $this->resource_business_id)->where('is_del', 1)->get()->toArray();
            $external_type_id = array_column($external_type_info, 'id', 'class_type_id');


            //获取数据上架列表
            $up_data = $obj->getTypeBookList(1, 1); //获取总数据量
            if ($up_data) {
                $limit = $this->limit;
                $total = $up_data['data']['totalRow'];
                $total_page = (int)ceil($total / $limit) + 1; //多增加一页，才能走else

                //获取所有数据和现在更新的数据做对比，如果没有则删除，有则不做处理
                $data_unique_id_all = $resourceModel->select('guid', 'data_unique_id')->where('resource_business_id', $this->resource_business_id)->where('is_del', 1)->get()->toArray();
                $data_unique_id_all = array_column($data_unique_id_all, 'guid', 'data_unique_id');

                for ($i = 1; $i <= $total_page; $i++) {
                    $data = $obj->getTypeBookList($i, $limit); //获取总数据量
                    if ($data) {
                        $result_id = '';
                        foreach ($data['data']['list'] as $key => $val) {
                            //获取数据详情
                            $class_type_id = $book_type_relation[$val['bookId']] ?? null; //获取书籍小类
                            if ($class_type_id) {
                                $val['type_id'] = $external_type_id[$class_type_id] ?? null; //获取我们数据库的类型id
                            } else {
                                $val['type_id'] = null;
                            }
                            //删除指定的值
                            unset($data_unique_id_all[$val['bookId']]);

                            $result = $resourceModel->addData($val);
                            $result_id .= $result . '、';
                        }
                        Log::channel('ytyscmdlog')->debug('全量同步上架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                    } else {
                        //删除本地更新不存在的数据
                        if (!empty($data_unique_id_all)) {
                            $result_id = '';
                            foreach ($data_unique_id_all as $key => $val) {
                                $del_id = $resourceModel->deleteData($key);
                                $result_id .= $del_id . '、';
                            }
                            Log::channel('ytyscmdlog')->debug('删除本地更新不存在的数据，处理完毕: ' . $result_id);
                        }
                        Log::channel('ytyscmdlog')->debug('全量同步上架数据处理完毕: 页数: ' . $i);
                        break;
                    }
                }
            }

            //下架接口不会返回剔除当前类的数据，所以在上面统一处理
            //获取数据下架列表,直接使用上面的流程就已经删除了指定数据
            // $down_data = $obj->getSoldOut();
            // if ($down_data) {
            //     //直接删除数据
            //     foreach ($down_data['data'] as $key => $val) {
            //         $resourceModel = new ResourceYtys();
            //         $resourceModel->deleteData($val['bookId']);
            //         $result_id .= $val['bookId'] . '、';
            //     }

            //     Log::channel('ytyscmdlog')->debug('全量同步下架数据，处理完毕: ' . $result_id);
            // } else {
            //     Log::channel('ytyscmdlog')->debug('暂无全量下架数据');
            //     return false;
            // }

            Log::channel('ytyscmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
            //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('ytyscmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
